package com.pb.wkflow.api.annotation;

import com.pb.infra.oth.util.SpringContextUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author 苗益辉
 * @date 2022/10/18 10:53
 */
@Service
public class GlobalWorkflowAnnotation {

    private static Map<String, WfTaskAnnotationService> serviceImplFactoryMap = new HashMap<>();

    public void init() {
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        // 根据接口获取配置的所有实现类
        Map<String, WfTaskAnnotationService> beans = applicationContext.getBeansOfType(WfTaskAnnotationService.class);
        // 遍历所有实现类
        Set<Entry<String, WfTaskAnnotationService>> entrySet = beans.entrySet();
        for (Entry<String, WfTaskAnnotationService> stringWfTaskAnnotationServiceEntry : entrySet) {
            WfTaskAnnotationService interfaceServiceImpl = stringWfTaskAnnotationServiceEntry.getValue();
            // 获取实现类的所有注解
            WfTaskAnnotation annotationValue = interfaceServiceImpl.getClass().getAnnotation(WfTaskAnnotation.class);
            if (null != annotationValue) {
                String name = annotationValue.name();
                serviceImplFactoryMap.put(name, interfaceServiceImpl);
            }
        }
    }

    public WfTaskAnnotationService getService(String processDefineKey) {
        WfTaskAnnotationService defaultService = serviceImplFactoryMap.get("DEFAULT");
        return serviceImplFactoryMap.getOrDefault(processDefineKey, defaultService);
    }
}
